package com.gradledemo.common.http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/*
 * Copyright (c) 2010-2015 LiZaoNet Inc. (http://www.lizaonet.com).
 * license: http://www.lizaonet.com
 */

/**
 * Created by charles on 13-12-5.
 */
public class DownloadUtils {

    /**
     * 下载文件到服务器
     *
     * @param from 来自的地址
     * @param to   需要存放的地址
     * @return 是否下载成功
     */
    public static boolean downloadFile(String from, String to) {
        boolean flag = false;

        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(from);
        try {
            HttpResponse response = client.execute(get);
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    File storeFile = new File(to);
                    FileOutputStream output = new FileOutputStream(storeFile);
                    InputStream input = entity.getContent();
                    byte b[] = new byte[1024];
                    int i = 0;
                    while ((i = input.read(b)) != -1) {
                        output.write(b, 0, i);
                    }
                    output.flush();
                    output.close();
                    flag = true;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }
}
